package main

import "fmt"

// 观察者模式
type Subject struct {
	observers []Observer
	state     string
}

type Observer interface {
	Update(string)
}

func (s *Subject) Attach(o Observer) {
	s.observers = append(s.observers, o)
}

func (s *Subject) SetState(state string) {
	s.state = state
	s.NotifyAll()
}

func (s *Subject) NotifyAll() {
	for _, o := range s.observers {
		o.Update(s.state)
	}
}

type ConcreteObserver struct {
	name string
}

func (o *ConcreteObserver) Update(state string) {
	fmt.Printf("%s received update: %s\n", o.name, state)
}

func main() {
	fmt.Println("Hello, playground")

	// 观察者模式示例
	fmt.Println("\nObserver Example:")
	subject := &Subject{}
	observer1 := &ConcreteObserver{name: "Observer 1"}
	observer2 := &ConcreteObserver{name: "Observer 2"}

	subject.Attach(observer1)
	subject.Attach(observer2)

	subject.SetState("State 1")
	subject.SetState("State 2")
}
